<template>
  <div class="home-view">
    <app-header />

    <main class="container">
      <section class="hero-section">
        <h1>欢迎来到斗图王</h1>
        <p class="subtitle">你的表情军火库，斗图永不输！</p>

        <search-bar
          :is-loading="false"
          @search="handleSearch"
        />
      </section>

      <section class="featured-section">
        <h2>热门标签</h2>
        <div class="tags-grid">
          <router-link
            v-for="tag in popularTags"
            :key="tag.id"
            :to="`/search?query=${tag.name}`"
            class="tag-card"
          >
            <div class="tag-count">{{ tag.count }}</div>
            <h3>{{ tag.name }}</h3>
            <p>{{ tag.count }} 个表情包</p>
          </router-link>
          <div v-if="isTagsLoading" class="loading-placeholder">
            <va-icon name="cached" size="large" />
            <p>加载中...</p>
          </div>
        </div>
      </section>

      <section class="latest-section">
        <div class="section-header">
          <h2>最新表情包</h2>
          <router-link to="/latest" class="view-all-link">
            查看全部 <va-icon name="arrow_forward" />
          </router-link>
        </div>

        <meme-grid
          :memes="latestMemes"
          :is-loading="isLatestLoading"
          :empty-message="'暂无最新表情包。成为第一个上传者！'"
        />
      </section>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import AppHeader from '../components/AppHeader.vue'
import SearchBar from '../components/SearchBar.vue'
import MemeGrid from '../components/MemeGrid.vue'
import { fetchLatestMemes, fetchPopularMemes, fetchTagStats } from '../api/memes'

const router = useRouter()

// 最新表情包
const latestMemes = ref([])
const isLatestLoading = ref(false)

// 热门表情包
const popularMemes = ref([])
const isPopularLoading = ref(false)

// 热门标签
const popularTags = ref([])
const isTagsLoading = ref(false)

// 标签背景颜色
const tagColors = [
  '#019587', '#01415B', '#005148', '#A6BC09', 
  '#5F7D8C', '#3F6C51', '#795548', '#607D8B'
]

onMounted(async () => {
  loadLatestMemes()
  loadPopularTags()
})

async function loadLatestMemes() {
  isLatestLoading.value = true

  try {
    const response = await fetchLatestMemes({ limit: 12 })
    latestMemes.value = response.data.memes
  } catch (error) {
    console.error('加载最新表情包失败:', error)
    // 演示用模拟数据
    latestMemes.value = getMockMemes(12)
  } finally {
    isLatestLoading.value = false
  }
}

async function loadPopularTags() {
  isTagsLoading.value = true

  try {
    const response = await fetchTagStats({ limit: 8, minCount: 2 })
    popularTags.value = response.data.map((tag, index) => ({
      id: tag.id,
      name: tag.name,
      count: tag.count,
      color: tagColors[index % tagColors.length]
    }))
  } catch (error) {
    console.error('加载热门标签失败:', error)
    // 演示用模拟数据
    popularTags.value = getMockTags(4)
  } finally {
    isTagsLoading.value = false
  }
}

function handleSearch(searchParams) {
  router.push({
    path: '/search',
    query: searchParams
  })
}

// 生成模拟表情包数据的辅助函数
function getMockMemes(count) {
  return Array.from({ length: count }, (_, i) => ({
    id: `mock-${i}`,
    title: `搞笑表情包 ${i + 1}`,
    imageUrl: `https://picsum.photos/seed/${i + 1}/400/300`,
    likes: Math.floor(Math.random() * 1000),
    views: Math.floor(Math.random() * 10000),
    createdAt: new Date(Date.now() - Math.floor(Math.random() * 1000000000)).toISOString()
  }))
}

// 生成模拟标签数据的辅助函数
function getMockTags(count) {
  const tagNames = ['搞笑', '动物', '游戏', '影视', '萌宠', '表情', '动漫', '明星']
  return Array.from({ length: count }, (_, i) => ({
    id: `mock-tag-${i}`,
    name: tagNames[i],
    count: Math.floor(Math.random() * 1000) + 100,
    color: tagColors[i % tagColors.length]
  }))
}
</script>

<style scoped>
.home-view {
  min-height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f8f9fa;
}

.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
  flex: 1;
}

.hero-section {
  padding: 3rem 0;
  text-align: center;
  width: 100%;
  border-radius: 0 0 20px 20px;
  margin-bottom: 2rem;
}

h1 {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
  color: var(--color-sailing-blue);
}

.subtitle {
  font-size: 1.25rem;
  color: var(--color-sailing-teal);
  margin-bottom: 2rem;
}

.featured-section,
.latest-section,
.popular-section {
  margin-bottom: 3rem;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  border-bottom: 2px solid var(--color-sailing-turquoise);
  padding-bottom: 0.75rem;
}

.section-header h2 {
  color: var(--color-sailing-blue);
}

.view-all-link {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  color: var(--color-sailing-turquoise);
  text-decoration: none;
  font-weight: 500;
}

.view-all-link:hover {
  color: var(--color-sailing-blue);
}

.tags-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 1.5rem;
  margin-top: 1.5rem;
}

.tag-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1.5rem;
  border-radius: 0.5rem;
  background-color: white;
  text-align: center;
  text-decoration: none;
  color: inherit;
  transition: transform 0.2s, box-shadow 0.2s;
  border: 1px solid var(--border-color);
  position: relative;
  overflow: hidden;
}

.tag-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  border-color: var(--color-sailing-lime);
}

.tag-count {
  position: absolute;
  top: 0;
  right: 0;
  background-color: var(--color-sailing-teal);
  color: white;
  padding: 0.25rem 0.5rem;
  font-size: 0.75rem;
  border-radius: 0 0 0 0.5rem;
}

.tag-card h3 {
  margin-bottom: 0.5rem;
  color: var(--color-sailing-teal);
  font-size: 1.25rem;
}

.tag-card p {
  color: var(--text-secondary);
  font-size: 0.875rem;
}

.loading-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 2rem;
  color: var(--text-secondary);
}

@media (max-width: 768px) {
  .hero-section {
    padding: 2rem 0;
  }

  h1 {
    font-size: 2rem;
  }

  .subtitle {
    font-size: 1rem;
  }

  .tags-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }
}
</style>
